﻿using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using rpc_service.cache;

namespace rpc_service.core.support.assembly.il.http.post;

public class ILSynchronizationPostHttpRequest : ILPostHttpRequest
{
    protected override bool isPass(string httpMethod, Type returnType)
    {
        if (httpMethod != "POST" && returnType != "Task".GetTypeByStr())
        {
            return false;
        }

        return true;
    }

    protected override void httpRequst(ILGenerator il, 
        LocalBuilder result, 
        LocalBuilder requestLocal, 
        LocalBuilder responseLocal,
        LocalBuilder receiveStreamLocal, 
        LocalBuilder readStreamLocal, 
        Type targetType, 
        MethodInfo targetMethod)
    {
        // 定义局部变量
        requestLocal = il.DeclareLocal("HttpWebRequest".GetTypeByStr());
        responseLocal = il.DeclareLocal("HttpWebResponse".GetTypeByStr());
        receiveStreamLocal = il.DeclareLocal("Stream".GetTypeByStr());
        readStreamLocal = il.DeclareLocal("StreamReader".GetTypeByStr());
        var paramLocal = il.DeclareLocal("string".GetTypeByStr());
        
        string pathUrl = targetType.GetCustomAttribute<RPCClass>()!.Path + "/" + targetMethod.GetCustomAttribute<RPCMethod>()!.Path;
        
        // 创建 HttpWebRequest 对象
        createHttpWebRequest(il, pathUrl, requestLocal);
        
        // 设置请求头
        createHeader(il, targetMethod, responseLocal);
        
        // 设置请求方法为 POST
        setRequestMethod(il, requestLocal, "POST");
        
        // 发送请求并获取响应
        sendRequest(il, requestLocal, responseLocal);
        
        createDataJson(il, paramLocal, targetMethod);

        writeJsonToRequest(il, requestLocal, paramLocal);
        
        // 获取响应流
        getResponse(il, responseLocal, receiveStreamLocal);
        
        // 读取响应内容并输出
        returnData(il, receiveStreamLocal, readStreamLocal, result);
    }
}